<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\Result;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:32',
            'phone' => 'required|integer|unique:user',
            'password' => 'required|string|between:6,32|confirmed',
            'gender' => 'string|size:1',
            'avatar' => 'url'
        ]);

        $user = $request->all();
        $user['password'] = Hash::make($user['password']);
        $user['api_token'] = hash('sha256', random_bytes(32));
        $user = User::create($user);

        return Result::OK('注册成功', [
            'id'=>$user->id,
            'token' => $user->api_token
        ]);
    }

    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $request->validate([
            'phone' => 'required|integer',
            'password' => 'required|string|between:6,32'
        ]);

        $user = User::where('phone', $request->phone)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            $token = $user->updateToken();
            return Result::OK('登录成功', [
                'id'=>$user->id,
                'name'=>$user->name,
                'token' => $token
            ]);
        }

        return Result::FAIL(422, '登录失败，手机号或密码错误');
    }

    /**
     * 用户退出
     */
    public function logout(Request $request)
    {
        $request->validate([
            'id' => 'required|integer'
        ]);

        User::where('id', $request->id)
        ->update(['api_token' => null]);

        return Result::OK('退出成功');
    }
}
?>